package com.vst.serverdatalib;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;

public class FileUtil {
	public static final String CACHE = "/vst/";
	public static final String BITCACHE = "thum";//
	public static final String JSONCACHE = "json_data";//
	private static final String TAG = "FileUtil";
	private static final int MB = 1024 * 1024;
	public static boolean isUseSdCard = false;

	public static void WriteString2File(String fileName, String content,
			Context context) {
		if (TextUtils.isEmpty(fileName) || TextUtils.isEmpty(content)) {
			return;
		}
		FileOutputStream fos = null;
		try {
			String path = mkdirs(context, JSONCACHE);
			if (TextUtils.isEmpty(path)) {
				throw new IllegalAccessException("sdcard and cache not exist");
			}
			File file = new File(path + fileName);
			if (file.exists()) {
				file.delete();
			}
			fos = new FileOutputStream(file);
			fos.write(content.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeIo(fos);
		}
	}

	public static void closeIo(Closeable os) {
		if (os != null) {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * @param path
	 * @return
	 */
	public static String ReadFile2String(String fileName, Context context) {
		FileInputStream fio = null;
		String path = mkdirs(context, JSONCACHE);
		if (TextUtils.isEmpty(path)) {
			return null;
		}
		File f = new File(path + fileName);
		if (!f.exists()) {
			return null;
		}
		try {
			fio = new FileInputStream(f);
			byte[] buf = new byte[1024];
			int len = -1;
			StringBuffer sb = new StringBuffer();
			while ((len = fio.read(buf, 0, buf.length)) != -1) {
				sb.append(new String(buf, 0, len));
			}
			return sb.toString();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeIo(fio);
		}
		return null;
	}

	/**
	 * 
	 * @return
	 */
	public static String getExternalStoragePath(Context context) {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			if (getAvailableStore() > 1000) {
				return android.os.Environment.getExternalStorageDirectory()
						.getPath() + CACHE;
			} else {
				return getCacheDiskPath(context);
			}
		}
		return null;
	}

	/**
	 * 
	 * @param context
	 * @return
	 */
	public static String getCacheDiskPath(Context context) {
		if (TextUtils.isEmpty(context.getApplicationContext().getCacheDir()
				.getAbsolutePath())) {
			return null;
		}
		String path = context.getApplicationContext().getCacheDir()
				.getAbsolutePath()
				+ CACHE;
		return path;
	}

	/**
	 * 
	 * @param dir
	 * @param context
	 * @return
	 */
	public static String mkdirs(Context context, String dir) {
		if (getExternalStoragePath(context) == null) {
			return null;
		}
		String path = getExternalStoragePath(context) + dir + "/";
		File cache = new File(path);
		if (!cache.exists()) {
			cache.mkdirs();
		}
		return path;
	}

	/**
	 * 
	 * @param filePath
	 * @return
	 */
	public static long getAvailableStore() {
		StatFs statFs = new StatFs(android.os.Environment
				.getExternalStorageDirectory().getPath());
		long blocSize = statFs.getBlockSize();
		long availaBlock = statFs.getAvailableBlocks();
		long availableSpare = availaBlock * blocSize;
		return availableSpare;
	}

	public static Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}

	public static Bitmap readBitMap(Context context, int resId, int width,
			int height) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		InputStream is = context.getResources().openRawResource(resId);
		return scaleBitmap(BitmapFactory.decodeStream(is, null, opt), width,
				height);
	}

	public static Bitmap scaleBitmap(Bitmap bm, int width, int height) {
		Matrix m = new Matrix();
		final int w = bm.getWidth();
		final int h = bm.getHeight();
		float sx = 0;
		if (width <= 0) {
			sx = w;
		} else {
			sx = (float) width / w;
		}
		float sy = 0;
		if (height <= 0) {
			sy = h;
		} else {
			sy = (float) height / h;
		}
		m.postScale(sx, sy);
		Bitmap dump = Bitmap.createBitmap(bm, 0, 0, w, h, m, true);
		return dump;
	}

	public static void clearAllCache(Context context) {
		String path = getExternalStoragePath(context);
		if (TextUtils.isEmpty(path)) {
			return;
		}
		File cachedFileDir = new File(path);
		deleteAll(cachedFileDir);
	}

	public static void deleteAll(File f) {
		try {
			File flist[] = f.listFiles();
			if (f == null || f.listFiles().length == 0) {
				return;
			}
			for (File file : flist) {
				if (file.isDirectory()) {
					deleteAll(file);
				} else {
					file.delete();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static long getFileSize(File f) {
		long size = 0;
		try {
			if (f == null || f.listFiles().length <= 0) {
				return size;
			}
			File flist[] = f.listFiles();
			for (File file : flist) {
				if (file.isDirectory()) {
					size = size + getFileSize(file);
				} else {
					size = size + file.length();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return size;
	}

	public static String formatFileSize(long fileS) {
		DecimalFormat df = new DecimalFormat("#0.00");
		String fileSizeString = "";
		if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "K";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}

	public static String getCacheInfo(Context context) {
		String path = getExternalStoragePath(context);
		if (TextUtils.isEmpty(path)) {
			return "0.00M";
		}
		File cachedFileDir = new File(path);
		return formatFileSize(getFileSize(cachedFileDir));
	}

	/**
	 * get remain room
	 * 
	 * @param context
	 * @return
	 */
	public static int freeSpaceOnSd(Context context) {
		StatFs stat = new StatFs(getExternalStoragePath(context));
		double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
				.getBlockSize()) / MB;
		return (int) sdFreeMB;
	}

	public static void saveBitmapToSdcard(Context context, Bitmap bitmap,
			String fileName) {
		String path = mkdirs(context, JSONCACHE);
		File file = new File(path + fileName);
		try {
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			bitmap.compress(CompressFormat.JPEG, 50, fos);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
